<template>
  <div>
    <el-form ref="dataForm" 
      :model="form" 
      label-width="100px"
      label-position="left"
      class="el-form"
      :rules="rules"
      >
      <el-form-item label="考核名称" prop="title">
        <el-input v-model="form.title" style="width: 450px;" placeholder="如“经理晋升考核、业务能力考核”"></el-input>
      </el-form-item>
      <el-form-item label="考核时间" prop="time">
        <el-date-picker
          v-model="form.time"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="考核对象" prop="resource1">
        <el-radio-group v-model="form.resource1">
          <el-radio label="按对象评分"></el-radio>
          <el-radio label="按职位评分"></el-radio>
        </el-radio-group>
        <div class="choose-user" @click="dialogVisible = true" prop="person">
          <div style="text-align: center;" v-if="members.length==0">
            <i class="el-icon-plus"></i>&nbsp;点击选择
          </div>
          <div class="choose-user-con" v-else>
            <div v-for="item in users" :key="item.key">
              <div class="user-con-item" v-show="item.selected">
                <el-avatar class="el-avatar" shape="square" :size="size" :src="item.photo"></el-avatar>
                <span class="user-con-text" v-text="item.label"></span>
              </div>
            </div>
          </div>
        </div>
        <span class="color-gray">最多可以选择25名评分对象</span>
      </el-form-item>
      <el-form-item label="考核模板" prop="template">
        <el-select v-model="form.template" style="width: 350px;" placeholder="请选择考核模板">
          <el-option 
            v-for="item in allTemplate"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="考核方式" prop="resource2">
        <el-radio-group v-model="form.resource2">
          <el-radio label="默认"></el-radio>
          <el-radio label="按指标组评分"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="评分人" prop="scorer">
        <div class="scorer">
          <div>权重总和：<span class="item-color" prop="weightCount">{{weightCount}}%</span></div>
          <div class="scorer-con" v-for="(scorer,index) in selectScorer" :key="scorer">
            <span class="right-split" v-text="index+1"></span>
            <el-select 
              v-model="selectScorer[index]"
              style="width: 180px"
              placeholder="请选择评分人"
              @change="updateSelectScorerInfo(index)"
              >
              <el-option 
                v-for="item in scorers"
                :key="item.key"
                :label="item.label" 
                :value="item.key"
                ></el-option>
            </el-select>
            <div class="weight">
              <span>权重</span>
              <el-input-number 
                v-model="weight[index]" 
                controls-position="right" 
                @change="numHandleChange($event, index)" 
                :min="0" 
                :max="100"
                :precision="2"
                style="width: 120px"
                class="num"
                ></el-input-number>%
                <i v-if="index != 0" 
                   class="el-icon-delete"
                   style="margin-left: 10px;cursor: pointer"
                   @click="deleteScorer(index)"></i>
            </div>
          </div>
          <div class="add-scorer" @click="addScorer">
            <i class="el-icon-plus"></i>&nbsp;添加下一位评分人
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button class="btn-color" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
    
    <el-dialog
      v-model="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div style="text-align: center">
        <p style="text-align: center; margin: 50px 0 20px;font-size: 18px">
          选择考核对象
        </p>
        <div style="text-align: center">
          <el-transfer
            v-model="members"
            style="text-align: left; display: inline-block;"
            filterable
            :titles="['全部对象', '选中对象']"
            :data="users"
            @change="handleChange"
          >
            <template #default="{ option }">
              <span>{{ option.label }}</span>
            </template>
          </el-transfer>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button class="backBtn" @click="cancelMember">取消</el-button> -->
          <el-button class="btn-color" @click="updateMember">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { beforeunloadHandler } from '../../utils/utils'
export default {
  data() {
    return {
      id: null, // 用来判断是新增 还是 复制
      form: {
        title: '',
        time: [],// 考核时间
        template: '',
        delivery: false,
        type: [],
        resource1: '按对象评分',
        resource2: '默认',
        desc: ''
      },
      chosenUser: [], // 考核对象  对应person
      allTemplate: [], // 考核模板内容
      scorers: [],  // 后端传来的全部评分人
      selectScorer: [''], // 选中的评分人 id
      selectScorerInfo: [], // 选中的评分人的全部信息
      weight: [0], // 选择的评分人的 权重 (0是预先给的值，为了能v-for渲染，之后会覆盖掉)
      rules: {
        name:  [
          { required: true, message: '请输入考核名称', trigger: 'blur' },
        ],
        // time:  [
        //   { type: 'date',required: true, message: '请选择考核时间', trigger: 'blur' },
        // ],
        person:  [
          { required: true, message: '请选择考核对象', trigger: 'blur' },
        ],
        template:  [
          { required: true, message: '请选择考核模板', trigger: 'blur' },
        ],
        resource2:  [
          { required: true, message: '请选择考核方式', trigger: 'blur' },
        ]
      },
      dialogVisible: false,
      users: [], // 用户数据  穿梭框数据
      members: [],  // 穿梭框选中数据
    }
  },
  created() {
    this.id = this.$route.params.id != undefined ? this.$route.params.id : null
    // console.log(this.$route.params.id == undefined);
    this.getAllTemplate() // 获取考核模板
    this.getUser() // 获取员工
    this.init()
  },
  methods: {
    init() {
      let data = {
        page: 1,
        length: 10
      }
      let id = this.id
      // console.log(id == null);
      if (id != "null" && id != null) {
        // 有id 是复制
        this.$http('checkList/selectCheckListById', 'post', {id}, false, resp => {
          if (resp.code == 200) {
            console.log(resp);
            let {list} = resp
            this.form.title = list.title
            this.form.time[0] = list.start_time
            this.form.time[1] = list.end_time
            this.allTemplate.map(item => {
              if (item.id == list.examTemplateId) {
                this.form.template = item.id
                return true
              }
            })
            this.weight = JSON.parse(list.weight)
            console.log(JSON.parse(list.scorer));
            
            // 只要name
            JSON.parse(list.scorer).forEach((item, index) => {
              this.selectScorer[index] = item.id
              this.updateSelectScorerInfo(index)
            })
            // 穿梭框选中数据
            let person = JSON.parse(list.person)
            person.forEach(item => {
              this.members.push(item.id)
            })
            // console.log(JSON.parse(list.scorer));
            
            this.handleChange()
          }
        })
      } else {
        // console.log('没有id');
        // 没有id 是新增
        this.$http('markTemplate/selectTemplateListBypages','post', data, false, resp => {
          if (resp.code == 200) {
            this.allTemplate = resp.page.list
          }
        })
      }
    },
    // 提交给后端
    onSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.weightCount != 100) {
            this.$message({
              message: '权重总和必须为100%',
              type: 'warning',
              duration: 1200
            })
            return false
          }
          let start_time = dayjs(this.form.time[0]).format('YYYY-MM-DD HH:mm:ss')
          let end_time = dayjs(this.form.time[1]).format('YYYY-MM-DD HH:mm:ss')
          // 整合person
          const person = []
          this.users.filter(item => {
            this.members.forEach(item2 => {
              if (item2 == item.key) {
                person.push({
                  id: item.key,
                  name: item.label
                })
              }
            })
          })
          // 整合scorer
          const scorer = []
          this.users.filter(item => {
            this.selectScorer.forEach(item2 => {
              if (item2 == item.key) {
                scorer.push({
                  id: item.key,
                  name: item.label
                })
              }
            })
          })
          let data = {
            title: this.form.title,
            start_time,
            end_time,
            person,
            examTemplateId: this.form.template,
            scorer,
            weight: this.weight
          }
          console.log(data);
          this.$http('checkList/addMark', 'post', data, false, resp => {
            if (resp.code == 200) {
              this.$message({
                message: '添加成功',
                type: 'success',
                duration: 1200
              })
              setTimeout(() => {
                this.$router.push({name: 'Exam', params: {tabClose: true}})
              }, 1200)
            }
          })
        } else {

          return false
        }
      })
    },
    // 获取考核模板
    getAllTemplate() {
      let data = {
        page: 1,
        length: 1000
      }
      this.$http('markTemplate/selectTemplateListBypages', 'post', data, false, resp => {
        if (resp.code == 200) {
          console.log(resp.page.list);
          
          this.allTemplate = resp.page.list
          // console.log(this.allTemplate);
        }
      })
    },
    // 获取全部用户
    getUser() {
			this.$http('checkList/getUser', 'get', null, false, (resp) => {
				let data = resp.data
				console.log(data)
        this.users = data // 穿梭框用
        this.scorers = data // 选择考评人用
				this.dataListLoading = false
      })
    },
    // 删除一条scorer
    deleteScorer(index) {
      this.selectScorerInfo.splice(index, 1)
      this.selectScorer.splice(index, 1)
      this.weight.splice(index, 1)
    },
    // 将选中的数据放入 selectScorerInfo(选择评分人时触发)
    updateSelectScorerInfo(index) {
      console.log(this.selectScorer);
      
      this.selectScorerInfo[index] = {
        scorer: this.selectScorer[index],
        weight: this.weight[index]
      }
      // console.log(this.selectScorerInfo);
      // console.log(this.selectScorer);
      // console.log(this.weight);
    },
    // 将选中的数据放入 selectScorerInfo(修改权重时触发)
    numHandleChange(currentValue, index) {
      this.updateSelectScorerInfo(index)
    },
    // 添加评分人
    addScorer() {
      // 预先在selectScorer里添加一个'请选择评分人'，选择之后再将这个值覆盖
      this.selectScorer.push('')
      this.weight.push(0)
    },
    // 穿梭框change事件(右边改变触发)
    handleChange() {
      // 先将users里的的selected全部设为false
      // this.users.map(user => {
      //   user.selected = false
      // })
      // 给选中的数据user里的selected改为true
      console.log(this.members);
      console.log(this.users);
      
      this.members.forEach(item => {
        this.users.map(user => {
          if (user.key == item) {
            // console.log(user);
            user.selected = true
          }
        })
      })
      // console.log(this.users);
      
    },
    // 穿梭框确定
    updateMember() {
      this.dialogVisible = false
    },
    // 穿梭框取消
    cancelMember() {
      this.dialogVisible = false
      // console.log(this.members);
      
    }
  },
  computed: {
    weightCount() {
      let sum = 0
      this.weight.forEach(item => sum += item);
      return sum
    }
  }
}
</script>

<style lang="scss" scoped>
@import './examAdd.scss';
</style>